package com.zhp.ggweather.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.zhp.ggweather.MainActivity;
import com.zhp.ggweather.app.App;
import com.zhp.ggweather.model.City;
import com.zhp.ggweather.model.WeatherInfo;

import android.app.Application;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;

public class GetWeatherTask extends AsyncTask<Void, Void, Integer> {

	private static final String BASE_URL = "http://sixweather.3gpk.net/SixWeather.aspx?city=%s";
	private static final int SCUESS = 0;
	private static final int SCUESS_YUJING = 1;
	private static final int FAIL = -1;
	private Handler mHandler;
	private City mCity;
	private App mApplication;

	public GetWeatherTask(City city,Handler handler) {
		super();
		this.mCity = city;
		this.mHandler = handler;
		mApplication = App.getInstance();
	}

	@Override
	protected Integer doInBackground(Void... params) {

		try {
			String url = String.format(BASE_URL,
					URLEncoder.encode("成都", "utf-8"));
			System.out.println("url的结果--->"+url);
			if (mApplication.getAllWeather() != null
					&& mApplication.getAllWeather().getCity()
							.equals(mCity.getName())) {
				return SCUESS;// 直接返回，不继续执行
			}
			// 再读取文件中的缓存信息
			String fileResult = ConfigCache.getUrlCache(mCity.getPinyin());
			if (!TextUtils.isEmpty(fileResult)) {
				WeatherInfo allWeather = XmlPullParseUtil
						.parseWeatherInfo(fileResult);
				if (allWeather != null) {
					mApplication.SetAllWeather(allWeather);
					return SCUESS;
				}
			}

			// 最后才执行网络请求
			String netResult = NetRequestUtil.requestDataForResult(url);
			if (!TextUtils.isEmpty(netResult)) {
				WeatherInfo allWeather = XmlPullParseUtil
						.parseWeatherInfo(netResult);
				if (allWeather != null) {
					mApplication.SetAllWeather(allWeather);
					ConfigCache.setUrlCache(netResult, mCity.getPinyin());
					String yujin = allWeather.getYujing();
					if (!TextUtils.isEmpty(yujin) && !yujin.contains("暂无预警"))
						return SCUESS_YUJING;
					return SCUESS;
				}
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	@Override
	protected void onPostExecute(Integer result) {
		
		if(result < 0 ){
			mHandler.sendEmptyMessage(MainActivity.GET_WEATHER_FAIL);// 获取天气信息失败
		}else{
			mHandler.sendEmptyMessage(MainActivity.GET_WEATHER_SCUESS);// 获取天气信息成功，通知主线程更新
			if(result == SCUESS_YUJING){
				mApplication.showNotification();
			}
		}
		super.onPostExecute(result);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}

}
